/**
 *    Copyright (C) 2007-2009 DIVIS GmbH (http://www.divis-hagen.de/)
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License as published by the Free Software Foundation; either
 *    version 3 of the License, or (at your option) any later version.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General
 *    Public License along with this library; if not, write to the
 *    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *    Boston, MA 02110-1301 USA
 */

package de.divis_hagen.json;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;


/**
 *
 * @author Aike J Sommer
 */
public class UnmarshallerImpl implements Unmarshaller {

    private final JSONContextImpl context;

    public UnmarshallerImpl(JSONContextImpl context) {
        this.context = context;
    }

    public Object unmarshall(InputStream in) throws JSONException {
        return unmarshall(new InputStreamReader(in));
    }

    public <Type> Type unmarshall(InputStream in,
            Class<Type> type) throws JSONException {
        return unmarshall(new InputStreamReader(in), type);
    }

    public Object unmarshall(Reader in) throws JSONException {
        return unmarshall(in, null);
    }

    public <Type> Type unmarshall(Reader in,
            Class<Type> type) throws JSONException {
        Map<String, Object> data;
        try {
            data = new JSONParser().parse(in);
        } catch (IOException ex) {
            throw new JSONException(ex);
        }

        System.out.println("parsed json: " + data);

        Set<TypeMeta.Complex> rootTypes = new HashSet<TypeMeta.Complex>(context.getRootTypes());
        if (type != null) {
            TypeMeta.Complex meta = (TypeMeta.Complex) context.meta(type);
            Set<TypeMeta.Complex> subTypes = new HashSet<TypeMeta.Complex>(meta.getSubTypes());
            for (Iterator<TypeMeta.Complex> it = rootTypes.iterator(); it.hasNext();) {
                TypeMeta.Complex sub = it.next();
                if (! subTypes.contains(sub) && ! meta.equals(sub)) {
                    it.remove();
                }
            }
        }
        return (Type) unmarshall(data, (Set) rootTypes);
    }

    private Object unmarshall(Map<String, Object> data, Collection<TypeMeta.Complex> types) {
        if (types.size() == 1) {
            return unmarshall(data, types.iterator().next());
        } else if (types.isEmpty()) {
            throw new IllegalArgumentException();
        } else {
            String name = (String) data.get("@type");
            if (name == null) {
                throw new IllegalArgumentException(data.toString());
            }

            for (TypeMeta.Complex type : types) {
                if (type.getName().equals(name)) {
                    return unmarshall(data, type);
                }
            }

            throw new IllegalArgumentException(data.toString());
        }
    }

    private Object unmarshall(Map<String, Object> data, TypeMeta.Complex<Object> type) {
        Object result = type.newInstance();
        for (TypeMeta.Property<Object, Object, Object> property : type.getProperties()) {
            if (property.getFlags().isReadOnly()) {
                continue;
            }
            Object value = data.get(property.getName());
            if (value == null) {
                continue;
            }

            if (property.getType().isPrimitive()) {
                property.getAccessor().set(result, null, ((TypeMeta.Primitive) property.getType()).decode(
                        (String) value));
            } else {
                throw new IllegalArgumentException();
            }
        }

        return result;
    }

}
